package com.steamedfish.auctionitemserver.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class AuthenticationSuccessHand implements AuthenticationSuccessHandler {

    private static final String SECRET = "shanfushanfu";

    //过期时间1分钟
    private static final int EXPIRES_TIME = 600000;



    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获取登陆角色
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        StringBuffer authoritiesBuffer = new StringBuffer();

        //遍历角存储到buffer中
        for (GrantedAuthority authority : authorities) {
            authoritiesBuffer.append(authority.getAuthority()).append(",");
        }

        //获取用户信息
//        authResult.getPrincipal()


        //定义token头部
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        //创建签发时间
        Date nowDate = new Date();
        //创建过期时间
        Date expiresDate = new Date(System.currentTimeMillis()+EXPIRES_TIME);

        String jwt = JWT.create()
                .withHeader(map)
                .withClaim("authorities", authoritiesBuffer.toString())
//                .withClaim("principal",)
                .withClaim("username", authentication.getName())
                .withIssuedAt(nowDate)
                .withExpiresAt(expiresDate)
//                .withSubject()
                .sign(Algorithm.HMAC256(SECRET));


        Map<String, String> resMap = new HashMap<>();
        resMap.put("token", jwt);
        resMap.put("msg", "Success");

        httpServletResponse.setContentType("application/json;chartset=utf-8");

        PrintWriter out = httpServletResponse.getWriter();
        String token = new ObjectMapper().writeValueAsString(resMap);
        out.write(token);
        out.flush();
        out.close();
    }
}